<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {ref, h} from "vue";
import { FormData, Mode } from "@/interfaces/components/Page";
import {FormTree} from "@/interfaces/components/Form";
import CdlForm from "@/components/form";
import CdlDescriptions from "@/components/descriptions"
import {InsuranceItem, Insure} from "@/interfaces/views/vehicle/insure";
import {Bills} from "@/interfaces/views/finance/bills";
import {DescriptionsTree} from "@/interfaces/components/Descriptions";
import CdlTable from "@/components/table";
import { TableTree } from "@/interfaces/components/Table";
import {useInsureAddRecordApi, useInsureInfoApi} from "@/api/vehicle/insure";
import { mergeObjects } from "@/utils/utilities";
import { createPopup } from "@/utils/createPopup";
import { ElMessage } from "element-plus";
import { appStore } from "@/store/modules/app";
import {cloneDeep} from "lodash";

const router = useRouter()
const route = useRoute()
const store = appStore()

if(route.query.id) initData()

const basicDetailTree: DescriptionsTree<Insure> = [
  {label: "关联车辆", prop: "licensePlate"},
  {label: "经办人", prop: "handler"},
  {label: "到期日期", prop: "expTime"},
  {label: "处理状态", prop: "status", dict: "insure_status"},
  {label: "备注", prop: "remark"},
]
const basicDetail = ref<FormData<Insure>>({
  id: undefined,
  licensePlate: "",
  handler: "",
  expTime: "",
  status: undefined,
  remark: ""
})
const recordFormTree: FormTree<Insure> = [
    [
      {label: "保险公司", component: "input", prop: "insuranceCompany", rule: [
          {required: true, message: "必须填写保险公司", trigger: "blur"}
        ]},
      {label: "投保日期", component: "datePicker", prop: "effectiveTime", rule: [
          {required: true, message: "必须选择投保日期", trigger: "change"}
        ]},
      {label: "保险单号", component: "input", prop: "insurancePolicyNum", rule: [
          {required: true, message: "必须填写保险单号", trigger: "blur"}
        ]},
      {label: "保险金额", component: "input", prop: "fee", type: "number", disabled: true},
      {label: "保额", component: "input", prop: "coverage", type: "number", disabled: true},
    ]
]
const recordForm = ref<FormData<Insure>>({
  insuranceCompany: "",
  effectiveTime: "",
  insurancePolicyNum: "",
  fee: "0",
  coverage: "0"
})
const insureTableTree: TableTree<InsuranceItem> = {
  colRule: [
    {ti: "保险类型", prop: "type", dict: "insure_type"},
    {ti: "保费（RMB）", prop: "fee"},
    {ti: "保额（RMB）", prop: "coverage"},
  ],
  control: [
    {name: "删除", type: "danger", method: removeInsuranceItem}
  ]
}
const insureFormTree: FormTree<InsuranceItem> = [
  [
    {label: "保险类型", component: "select", prop: "type", options: store.getFormatDict("insure_type"),
      optionProps: {label: "dictLabel", value: "dictValue"}, placeholder: "请选择一个保险类型", rule: [
        {required: true, message: "必须选择保险类型", trigger: "change"},
      ]},
    {label: "保费", component: "input", prop: "fee", type: "number", rule: [
        {required: true, message: "必须填写保费", trigger: "blur"}
      ]}
  ],
  [
    {label: "保额", component: "input", prop: "coverage", type: "number", rule: [
        {required: true, message: "必须填写保额", trigger: "blur"}
      ]}
  ]
]
const insureForm = ref<FormData<InsuranceItem>>({
  type: undefined,
  fee: "",
  coverage: ""
})
const insureData = ref<FormData<InsuranceItem[]>>([])
const billData = ref<FormData<Bills[]>>([])
const billForm = ref<FormData<Bills>>({

})
const recordRef = ref()
const billRef = ref()

/**
 * 提交
 */
async function submit(){
  const record = await recordRef.value.parentSubmit()
  const basic = cloneDeep(basicDetail.value)
  const insure = cloneDeep(insureData.value)
  const data = Object.assign({}, record, basic)
  data.insuranceItems = insure
  data.status = 2
  useInsureAddRecordApi(data).then(()=>{
    ElMessage.success("提交成功！自动返回上一页")
    fallbackPage()
  })
}

/**
 * 初始化数据
 */
function initData(){
  useInsureInfoApi(route.query.id as string).then(res => {
    const {bills, insuranceItems, ...rest} = res.data
    mergeObjects(basicDetail.value, rest)
    mergeObjects(recordForm.value, rest)
    insureData.value = insuranceItems
    billData.value = bills
  })
}

/**
 * 移除保险项
 */
function removeInsuranceItem(data: InsuranceItem){
  insureData.value = insureData.value.filter(item => item !== data)
  recordForm.value.fee = (parseInt(recordForm.value.fee!) - parseInt(data.fee)).toString()
  recordForm.value.coverage = (parseInt(recordForm.value.coverage!) - parseInt(data.coverage)).toString()
}

/**
 * 新增保险项
 */
function openInsureItemInsert(){
  createPopup("新增保险项", h(CdlForm, {
    templateTree: insureFormTree,
    model: insureForm.value
  }), "add", popupCallBack)
}

/**
 * 保险项发生变化的处理
 * @param data
 * @constructor
 */
function InsureItemHandle(data: InsuranceItem){
  recordForm.value.fee = (parseInt(recordForm.value.fee!) + parseInt(data.fee)).toString()
  recordForm.value.coverage = (parseInt(recordForm.value.coverage!) + parseInt(data.coverage)).toString()
}
/**
 * 回调处理
 * @param mode
 * @param val
 */
function popupCallBack(mode: Mode, val?: any){
  switch (mode){
    case "add":
      insureData.value.push(val)
      ElMessage.success("添加成功！")
      InsureItemHandle(val)
      break
  }
}
/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
  <el-card style="position: relative">
    <button class="back_btn" @click="fallbackPage"></button>
    <h1 class="top_line">基础信息</h1>
    <el-divider></el-divider>
    <CdlDescriptions :model="basicDetail" :template-tree="basicDetailTree"></CdlDescriptions>
    <div class="row">
      <h1 class="top_line">记录信息</h1>
      <el-button type="primary" size="small" @click="openInsureItemInsert">添加保险项</el-button>
    </div>
    <el-divider></el-divider>
    <CdlForm ref="recordRef" :model="recordForm" :template-tree="recordFormTree"></CdlForm>
    <CdlTable :data="insureData" :template-tree="insureTableTree" border></CdlTable>
    <div class="footer_btn" style="margin-top: 15px">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="fallbackPage">取消</el-button>
    </div>
  </el-card>
</template>
